﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WindowsInput.Native;
using WindowsInput;
using Microsoft.Win32;
using LessonStudio.Models;
using System.Xml.Linq;

namespace LessonStudio.UI
{
    /// <summary>
    /// Interaction logic for PdfConvertorWnd.xaml
    /// </summary>
    public partial class PdfConvertorWnd : UserControl
    {
        public event Action OnCancel;
        public PdfConvertorWnd()
        {
            InitializeComponent();
            InitUI();
            BindEvents();
        }

        #region 事件处理
        private void OnWndLoaded(object sender, RoutedEventArgs e)
        {
            //
        }

        private void OnWindowKeyDown(object sender, KeyEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.KeyboardDevice.Modifiers);
            System.Diagnostics.Debug.WriteLine(e.Key);
            //
            if (e.Key == Key.Right)
            {
                //翻页
                //NextPage();

                btnNextPage.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                e.Handled = true;
            }
            else if (e.Key == Key.Left)
            {
                //翻页
                btnPrevPage.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                e.Handled = true;
                //PrevPage();
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.Up)
            {
                moonPdfPanel.GotoFirstPage();
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.Down)
            {
                moonPdfPanel.GotoLastPage();
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.O)
            {
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.C)
            {
                e.Handled = true;
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.E)
            {
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.H)
            {
                //隐藏上面的各个按钮
            }
            else if (e.Key == Key.Back)
            {
                //返回
                Close();
                e.Handled = true;
            }
        }

        private void OnButtonOpenFileClick(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Filter = "PDF文件(*.pdf)|*.pdf";
            dialog.Multiselect = false;
            if (dialog.ShowDialog().GetValueOrDefault())
            {
                //转换一个PDF文件
                _pdfFilePath = dialog.FileName;

                _imageDir = System.IO.Path.GetDirectoryName(_pdfFilePath);
                _imageDir = System.IO.Path.Combine(_imageDir, "Images");
                System.Diagnostics.Debug.WriteLine(_imageDir);
                //
                moonPdfPanel.Visibility = Visibility.Collapsed;
                moonPdfPanel.OpenFile(_pdfFilePath);
                //moonPdfPanel.ZoomToHeight();
                moonPdfPanel.Visibility = Visibility.Visible;
            }
        }

        private void OnButtonSaveToImageFileClick(object sender, RoutedEventArgs e)
        {
            //循环
            this.IsEnabled= false;
            moonPdfPanel.GotoFirstPage();
            System.Threading.Thread.Sleep(1000);
            int index = 0;
            for(index=0;index<moonPdfPanel.TotalPages;index++)
            {
                //保存
                SaveImage(index + 1);
                moonPdfPanel.GotoNextPage();
                System.Threading.Thread.Sleep(1000);
            }
            SaveImage(index + 1);
            this.IsEnabled = true;
        }

        private void OnButtonPrevPageClick(object sender, RoutedEventArgs e)
        {
            //首先备份画笔
            try
            {
                if (moonPdfPanel.TotalPages > 0)
                {
                    SaveImage(moonPdfPanel.GetCurrentPageNumber());
                }

                moonPdfPanel.GotoPreviousPage();
            }
            catch
            {
            }
        }

        private void OnButtonNextPageClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (moonPdfPanel.TotalPages > 0)
                {
                    SaveImage(moonPdfPanel.GetCurrentPageNumber());
                }

                //首先备份画笔
                moonPdfPanel.GotoNextPage();
            }
            catch
            {
            }
        }


        #endregion

        #region 辅助函数
        string _pdfFilePath = null;
        string _imageDir = null;

        void InitUI()
        {
        }

        void BindEvents()
        {
            this.Loaded += OnWndLoaded;
            this.KeyDown += OnWindowKeyDown;
            btnPrevPage.Click += OnButtonPrevPageClick;
            btnNextPage.Click += OnButtonNextPageClick;
            btnOpenFile.Click += OnButtonOpenFileClick;
            btnSaveToImageFile.Click += OnButtonSaveToImageFileClick;
            btnFitToWidth.Click += OnButtonFitToWidthClick;
            btnFitToHeight.Click += OnButtonFitToHeightClick;
            btnClose.Click += (s, e) => { Close(); };
        }

        private void OnButtonFitToHeightClick(object sender, RoutedEventArgs e)
        {
            moonPdfPanel.ZoomToHeight();
        }

        private void OnButtonFitToWidthClick(object sender, RoutedEventArgs e)
        {
            moonPdfPanel.ZoomToWidth();
        }

        void Close()
        {
            if(moonPdfPanel.TotalPages>0)
            {
                SaveImage(moonPdfPanel.GetCurrentPageNumber());
            }
            OnCancel?.Invoke();
        }


        void SaveImage(int index)
        {
            try
            {
                if (!string.IsNullOrEmpty(_imageDir))
                {
                    var imageFilePath = System.IO.Path.Combine(_imageDir, string.Format("{0:D5}.jpg", index));

                    //
                    //var image = GetImageControl(moonPdfPanel);
                    var image = moonPdfPanel.FindImageControl();
                    if (image != null)
                    {
                        GetPicFromControl(image as Image, imageFilePath);

                    }
                    else
                    {
                        GetPicFromControl(moonPdfPanel, imageFilePath);
                    }

                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        //截屏函数
        private void GetPicFromControl(FrameworkElement element, String outputPath, String type = "JPEG")
        {
            //96为显示器DPI
            //位图 宽度  高度   水平DPI  垂直DPI  位图的格式    
            //高度+100保证整个图都能截取: 我们这里不加
            //
            //var dpi = DisplayInformation.GetForCurrentView().LogicalDpi;
            //var bmp = new WriteableBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96., 96, PixelFormats.Pbgra32, null);
            //这里的宽度和高度，以及分辨率很大程度上决定了图片的质量
            //WPF默认是96dpi渲染
            var bitmapRender = new RenderTargetBitmap((int)element.ActualWidth * 3, (int)element.ActualHeight * 3, 96 * 3, 96 * 3, PixelFormats.Pbgra32);
            //控件内容渲染RenderTargetBitmap
            bitmapRender.Render(element);
            BitmapEncoder encoder = null;
            //选取编码器
            switch (type.ToUpper())
            {
                case "BMP":
                    encoder = new BmpBitmapEncoder();
                    break;
                case "GIF":
                    encoder = new GifBitmapEncoder();
                    break;
                case "JPEG":
                    var jpeg = new JpegBitmapEncoder();
                    jpeg.QualityLevel = 80;
                    encoder = jpeg;
                    break;
                case "PNG":
                    encoder = new PngBitmapEncoder();
                    break;
                case "TIFF":
                    encoder = new TiffBitmapEncoder();
                    break;
                default:
                    break;
            }

            //对于一般的图片，只有一帧，动态图片是有多帧的。
            encoder.Frames.Add(BitmapFrame.Create(bitmapRender));//添加图
            if (!Directory.Exists(System.IO.Path.GetDirectoryName(outputPath)))
                Directory.CreateDirectory(System.IO.Path.GetDirectoryName(outputPath));
            using (var file = File.Create(outputPath))//存储文件
                encoder.Save(file);
        }

        private FrameworkElement GetImageControl(UIElementCollection uiControls)
        {
            foreach (UIElement element in uiControls)
            {
                if (element is Image)
                {
                    return element as Image;
                }
                else if (element is Grid)
                {
                    return GetImageControl((element as Grid).Children);
                }
                else if (element is Expander)
                {
                    if ((element as Expander).Content is StackPanel)
                    {
                        StackPanel sa = (element as Expander).Content as StackPanel;
                        return GetImageControl(sa.Children);
                    }
                    else if ((element as Expander).Content is Grid)
                    {
                        Grid sa = (element as Expander).Content as Grid;
                        return GetImageControl(sa.Children);
                    }
                    else
                    {
                        return null;    
                    }
                }
                else if (element is StackPanel)
                {
                    return GetImageControl((element as StackPanel).Children);
                }
                else if (element is ScrollViewer)
                {
                    StackPanel sp = (element as ScrollViewer).Content as StackPanel;
                    return GetImageControl(sp.Children);
                }
                else if (element is TabControl)
                {
                    return GetImageControl(element as TabControl);
                }
                else
                {
                    return null;
                }
            }

            return null;
        }

        private FrameworkElement GetImageControl(FrameworkElement element)
        {
            if (element is Image)
            {
                return element;
            }
            else if (element is Grid)
            {
                return GetImageControl((element as Grid).Children);
            }
            else if (element is Expander)
            {
                if ((element as Expander).Content is StackPanel)
                {
                    StackPanel sa = (element as Expander).Content as StackPanel;
                    return GetImageControl(sa.Children);
                }
                else if ((element as Expander).Content is Grid)
                {
                    Grid sa = (element as Expander).Content as Grid;
                    return GetImageControl(sa.Children);
                }
                else
                { return null; }
            }
            else if (element is StackPanel)
            {
                return GetImageControl((element as StackPanel).Children);
            }
            else if (element is ScrollViewer)
            {
                StackPanel sp = (element as ScrollViewer).Content as StackPanel;
                return GetImageControl(sp.Children);

                //ScrollViewer不具有Children属性，无法对其进行遍历，但是具有Content属性，作为容器型控件，一般都可以通过这样的方法来解决。
            }
            else if (element is TabControl)
            {
                return GetImageControl(element as TabControl);
            }
            else
            {
                return null;
            }
        }

        #endregion

    }
}
